package com.win.app;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.li.utils.SignUtil;

/**
 * Servlet implementation class WeixinInit
 */
@WebServlet("/WeixinInit")
public class WeixinInit extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public WeixinInit() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 微信加密签名
				String signature = request.getParameter("signature");
				// 时间戳
				String timestamp = request.getParameter("timestamp");
				// 随机数
				String nonce = request.getParameter("nonce");
				// 随机字符串
				String echostr = request.getParameter("echostr");
				System.out.println("===============>微信验证"+signature+"   "+timestamp+"   "+nonce+"   "+echostr);
				PrintWriter out;
				try {
					out = response.getWriter();
					// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
					if (SignUtil.checkSignature("liandyao",signature, timestamp, nonce)) {
						out.print(echostr);
					}
					out.close();
					out = null;
				} catch (IOException e) { 
					e.printStackTrace();
				}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
